import {createAsyncThunk, createSlice} from "@reduxjs/toolkit";
import {message as AntMessage} from "antd";



const themeSlice = createSlice({
    name: 'theme',
    initialState: {
        isDark: false,
    },
    reducers: {
        // 储存token
        SET_ISDARK: (state) => {
            state.isDark = !state.isDark
        },

    },

    // https://zhuanlan.zhihu.com/p/382487951
    // 一般用于处理异步操作，这里是Pending: 当异步操作开始时，Fulfilled: 当异步操作成功完成时，Rejected: 当异步操作遇到错误时
    extraReducers: (builder) => {
        // builder.addCase(getUserInfoSlice.pending, () => {
        //     // console.log('pending 进行中');
        // })
        // builder.addCase(getUserInfoSlice.fulfilled, (state, { payload }) => {
        //     // console.log( '1 fulfilled', { payload, state } )
        // })
        // builder.addCase(getUserInfoSlice.rejected, (state, action) => {
        //     // userSlice.actions.CLEAR_USER_INFO()
        // })
    }


})

export const {SET_ISDARK,} = themeSlice.actions
export const getLogin = createAsyncThunk("user/login",
    async (params:any, thunkAPI) => {
        try {
            const   res:any = await login(params)


            if (res.code === 200) {
                if(res.token){
                    // thunkAPI.dispatch(SET_TOKEN(res.token))
                }

            } else {
                AntMessage.warning(res.msg || '登录失败')
            }
        } catch (error) {
            console.log(error, 'error')
        }
    })



export const loginOut = createAsyncThunk(
    'user/loginOut',
    async(params, thunkAPI) => {
        try {
            // const response = {
            //     code: 200,
            //     message: 'success'
            // }
            // const { code, data } = response
            const res:any = await logout()

            if (res.code === 200) {
                thunkAPI.dispatch(REMOVE_TOKEN())
                location.href = '/';
                // window.location.reload()
                return {}
            } else {
                return thunkAPI.rejectWithValue(res.data.message || '登出失败')
            }
        } catch (err) {
            return thunkAPI.rejectWithValue(err.response.data || '登出失败')
        }
    }
)


const userReducer = themeSlice.reducer
export default userReducer
